package com.gz.logistics.app;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.logistics.R;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.SingleOrderDeliveryStatusChangeListener;
import com.gz.logistics.library.listener.SingleOrderLoggisticsStatusChangeListener;
import com.gz.logistics.library.pojo.OrderInfo;
import com.gz.logistics.library.pojo.ProductInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.library.util.Tools;
import com.gz.logistics.util.ToastUtils;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {
    private static String TAG = OrderDetailActivity.class.getSimpleName();
    private OrderInfo ClickOrder;//需要显示的订单
    private ImageView iv_action_back;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private TextView tv_order_number;
    private TextView tv_create_time;
    private TextView tv_receiver_name;
    private TextView tv_receiver_phone;
    private TextView tv_receiver_address;

    private TextView tv_receiver_cpucbt; //提货方式
    private TextView tv_pay_type;  // 支付方式
    private TextView tv_money;  // 应收金额
    private TextView tv_notes;  // 备注

    private LinearLayout productList;
    private TextView tv_order_price;
    private TextView tv_logistic_status;
    private TextView tv_delivery_status;
    private Button btn_logistics_confirm;
    private Button btn_delivery_confirm;
    private Dialog mLoadingData;

    private UserInfo userInfo;
    private MySingleOrderLoggisticsStatusChangeListener mSingleOrderLoggisticsStatusChangeListener;
    private MySingleOrderDeliveryStatusChangeListener mSingleOrderDeliveryStatusChangeListener;

    private boolean isChaged = false;// 标记该订单的转状态是否改变，如果改变了，返回之前页面后刷新界面，没改变则不

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_head_layout);//自定义ActionBar布局
        ClickOrder = (OrderInfo)this.getIntent().getSerializableExtra("clickOrder");



        userInfo =  IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));

        initView();
        initListener();
        initData();
    }

    @Override
    protected void onDestroy() {
        mSingleOrderLoggisticsStatusChangeListener.release();
        mSingleOrderDeliveryStatusChangeListener.release();
        super.onDestroy();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_actionbar_up:
                if (isChaged){
                    Intent intent = getIntent();
                    intent.putExtra("changedOrderSn",ClickOrder.getSn());
                    setResult(Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE,intent);
                }
                isChaged = false;
                finish();
                break;
            case R.id.btn_delivery_confirm:
                mLoadingData.show();
                if (ClickOrder != null){
                    if (!isChaged){  // 订单状态发生改变，则把该订单编号返回给之前的界面
                        isChaged = true;
                    }
                    IOrder.getInstance().singalorderDeliveryStatusSign(ClickOrder.getSn(),mSingleOrderDeliveryStatusChangeListener);
                }
                break;
            case R.id.btn_logistics_confirm:
                mLoadingData.show();
                if (ClickOrder != null){
                    if (!isChaged){  // 订单状态发生改变，则把该订单编号返回给之前的界面
                        isChaged = true;
                    }
                    IOrder.getInstance().singalorderLogisticsStatusSign(ClickOrder.getSn(),mSingleOrderLoggisticsStatusChangeListener);
                }
                break;
        }

    }

    /**
     * 如果店家物理返回按钮返回上一个页面， 对是否设置返回值进行判断设置
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isChaged){
                Intent intent = getIntent();
                intent.putExtra("changedOrderSn",ClickOrder.getSn());
                setResult(Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE,intent);
            }
            isChaged = false;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化控件
     */
    public void initView(){
        iv_action_back = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        tv_order_number = (TextView) this.findViewById(R.id.tv_order_number);
        tv_create_time = (TextView) this.findViewById(R.id.tv_create_time);
        tv_receiver_name = (TextView) this.findViewById(R.id.tv_receiver_name);
        tv_receiver_phone = (TextView) this.findViewById(R.id.tv_receiver_phone);
        tv_receiver_address = (TextView) this.findViewById(R.id.tv_receiver_address);
        tv_receiver_cpucbt = (TextView) this.findViewById(R.id.tv_receiver_cpucbt);
        tv_pay_type = (TextView) this.findViewById(R.id.tv_pay_type);
        tv_money = (TextView) this.findViewById(R.id.tv_money);
        tv_notes = (TextView) this.findViewById(R.id.tv_notes);


        productList = (LinearLayout) this.findViewById(R.id.list_products);
        tv_order_price = (TextView) this.findViewById(R.id.tv_order_price);
        tv_logistic_status = (TextView) this.findViewById(R.id.tv_logistic_status);
        tv_delivery_status = (TextView) this.findViewById(R.id.tv_delivery_status);

        btn_logistics_confirm = (Button) this.findViewById(R.id.btn_logistics_confirm);
        btn_delivery_confirm = (Button) this.findViewById(R.id.btn_delivery_confirm);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);


    }

    /**
     * 初始化监听器
     */
    public void initListener(){
        iv_action_back.setOnClickListener(this);
        btn_delivery_confirm.setOnClickListener(this);
        btn_logistics_confirm.setOnClickListener(this);
        mSingleOrderLoggisticsStatusChangeListener = new MySingleOrderLoggisticsStatusChangeListener(this);
        mSingleOrderDeliveryStatusChangeListener = new MySingleOrderDeliveryStatusChangeListener(this);
    }

    /**
     * 初始化数据，给控件绑定数据
     */
    public void initData(){
        tv_actionbar_title.setText("订单详情");
        if (userInfo != null){
            tv_actionbar_deliveryName.setText("配送员："+userInfo.getUser_name());
        }
        if (ClickOrder == null ){
            return ;
        }
        tv_order_number.setText("编号："+ClickOrder.getSn());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm");
        tv_create_time.setText(format.format(new Date(ClickOrder.getCreate_at()*1000)));
        tv_receiver_name.setText("收货人姓名："+ClickOrder.getReceiver_name());
        tv_receiver_phone.setText("收货人电话："+ClickOrder.getReceiver_tel());
        tv_receiver_address.setText("收货人地址："+ClickOrder.getReceiver_add());
        String cpucbtType = ClickOrder.getCpucbt() == Define.FLAG_CPUCBT_DELIVERY ? "送货上门":"自取";
        String payType = ClickOrder.getPay_type() == Define.FLAG_PAY_TYPE_ONLINE ? "在线支付":"货到付款";
        tv_receiver_cpucbt.setText("提货方式："+cpucbtType);
        tv_pay_type.setText("支付方式："+payType);
        tv_money.setText("应收金额：￥"+ClickOrder.getMoney());
        tv_notes.setText("备注："+ClickOrder.getNotes());
        tv_order_price.setText("￥"+ClickOrder.getMoney());

        String logistic_status = ClickOrder.getTrans_status() == Define.FLAG_TRANS_STATUS_SIGNED ? "已签收":"未签收";
        String deliver_status = ClickOrder.getSign_status() == Define.FLAG_DELEVERY_STATUS_SIGNED ? "已签收":"未签收";
        tv_logistic_status.setText(logistic_status);
        tv_delivery_status.setText(deliver_status);


        if (ClickOrder.getTrans_status() == Define.FLAG_TRANS_STATUS_NO_SIGN){
            // 如果还未进行物流签收，则把"物流"置为可见,"业务签收"按钮置为不可见,
            btn_logistics_confirm.setVisibility(View.VISIBLE);
            btn_delivery_confirm.setVisibility(View.INVISIBLE);
        }else{
            // 如果已经物流签收了,"物流"置为不可见
            btn_logistics_confirm.setVisibility(View.INVISIBLE);
            if (ClickOrder.getSign_status() == Define.FLAG_DELEVERY_STATUS_SIGNED){
                //如果业务也签收了，物流按钮 置为不可见
                btn_delivery_confirm.setVisibility(View.INVISIBLE);
            }else{
                // 业务还未签收，"业务"置为可见
                btn_delivery_confirm.setVisibility(View.VISIBLE);
            }

        }

        // 生成产品条目列表
        List<ProductInfo> products = ClickOrder.getProductInfos();
        productList.removeAllViews();
        for (int j = 0 ; j < products.size() ; j++ ){
            ProductInfo productInfo = products.get(j);

            View productItemView = LayoutInflater.from(this).inflate(R.layout.home_orders_products_item, null);
            TextView tv_product_name = (TextView) productItemView.findViewById(R.id.tv_product_name);
            TextView tv_total_price = (TextView)productItemView.findViewById(R.id.tv_total_price);

            tv_product_name.setText(productInfo.getProduct_name());
           // tv_product_name.setTextSize(Tools.sp2px(this, 13));

            tv_total_price.setText(productInfo.getProduct_num() + " × " + productInfo.getProduct_price());
           // tv_total_price.setTextSize(Tools.sp2px(this,13));

            // 如果是最后一个条目，则把分割线的宽度设置成和父窗体一样  （没效果啊 ！什么原因？）
            ImageView divider = (ImageView) productItemView.findViewById(R.id.vv_divider);

            if (j == products.size() - 1){

                ((LinearLayout.LayoutParams)divider.getLayoutParams()).leftMargin = 0 ;

            }else{

                ((LinearLayout.LayoutParams)divider.getLayoutParams()).leftMargin = Tools.dip2px(this, 15);

            }
            productList.addView(productItemView);
        }






    }


    /**
     * 单订单物流签收 回调接口
     */
    private static class MySingleOrderLoggisticsStatusChangeListener extends SingleOrderLoggisticsStatusChangeListener{
        private OrderDetailActivity mOuter;

        public MySingleOrderLoggisticsStatusChangeListener(OrderDetailActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OrderDetailActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            mOuter.btn_logistics_confirm.setVisibility(View.INVISIBLE);
            mOuter.btn_delivery_confirm.setVisibility(View.VISIBLE);
            mOuter.tv_logistic_status.setText("已签收");
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "物流签收成功");
        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"物流签收失败");
        }
    }

    /**
     * 单订单业务签收回调接口
     */
    private class MySingleOrderDeliveryStatusChangeListener extends  SingleOrderDeliveryStatusChangeListener{
        private OrderDetailActivity mOuter;

        public MySingleOrderDeliveryStatusChangeListener(OrderDetailActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OrderDetailActivity>(mOuter);
        }

        @Override
        public void onHasNotSignLogistic() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"请先完成该订单的物流签收");

        }

        @Override
        public void onResponseSuccess() {
            mOuter.btn_logistics_confirm.setVisibility(View.INVISIBLE);
            mOuter.btn_delivery_confirm.setVisibility(View.INVISIBLE);
            mOuter.tv_delivery_status.setText("已签收");
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "业务签收成功");
        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"业务签收失败");
        }
    }
}
